'use client';

import { useState, useEffect } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { toast } from "react-hot-toast";
import styles from "../forgot-password.module.css";

const VerifyCodePage = () => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const email = searchParams.get("email");
  const [loading, setLoading] = useState(false);
  const [timer, setTimer] = useState(60); // 倒计时
  const [canResend, setCanResend] = useState(false);

  // 表单状态
  const [formData, setFormData] = useState({
    code: "",
    newPassword: "",
    confirmPassword: ""
  });

  // 验证邮箱参数是否存在
  useEffect(() => {
    if (!email) {
      router.push("/dashboard/forgot-password");
    }
  }, [email, router]);

  // 倒计时逻辑
  useEffect(() => {
    if (timer > 0) {
      const interval = setInterval(() => {
        setTimer(prev => prev - 1);
      }, 1000);
      return () => clearInterval(interval);
    } else {
      setCanResend(true);
    }
  }, [timer]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 重新发送验证码
  const handleResend = async () => {
    setLoading(true);
    setCanResend(false);
    setTimer(60);

    try {
      const res = await fetch("/api/auth/forgot-password/send-code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email })
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "重新发送失败");
      }

      toast.success("验证码已重新发送");
    } catch (err) {
      toast.error(err.message);
    } finally {
      setLoading(false);
    }
  };

  // 提交重置密码
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const res = await fetch("/api/auth/forgot-password/reset", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email,
          ...formData
        })
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "重置密码失败");
      }

      toast.success(data.message);
      router.push("/dashboard/login");
    } catch (err) {
      toast.error(err.message);
    } finally {
      setLoading(false);
    }
  };

  if (!email) {
    return null; // 邮箱参数不存在时不渲染
  }

  return (
    <div className={styles.container}>
      <h1 className={styles.title}>验证并重置密码</h1>
      <p className={styles.subtitle}>
        验证码已发送至 <span className={styles.highlight}>{email}</span>，请输入验证码并设置新密码
      </p>

      <form onSubmit={handleSubmit} className={styles.form}>
        {/* 验证码输入 */}
        <div className={styles.formGroup}>
          <label className={styles.label}>验证码</label>
          <div className={styles.codeContainer}>
            <input
              type="text"
              name="code"
              value={formData.code}
              onChange={handleChange}
              className={styles.input}
              placeholder="6位数字验证码"
              maxLength="6"
              required
            />
            <button
              type="button"
              onClick={handleResend}
              disabled={!canResend || loading}
              className={styles.resendButton}
            >
              {canResend ? "重新发送" : `重新发送(${timer}s)`}
            </button>
          </div>
        </div>

        {/* 新密码 */}
        <div className={styles.formGroup}>
          <label className={styles.label}>新密码</label>
          <input
            type="password"
            name="newPassword"
            value={formData.newPassword}
            onChange={handleChange}
            className={styles.input}
            placeholder="请设置新密码"
            required
          />
        </div>

        {/* 确认密码 */}
        <div className={styles.formGroup}>
          <label className={styles.label}>确认新密码</label>
          <input
            type="password"
            name="confirmPassword"
            value={formData.confirmPassword}
            onChange={handleChange}
            className={styles.input}
            placeholder="请再次输入新密码"
            required
          />
        </div>

        <button
          type="submit"
          disabled={loading}
          className={styles.button}
        >
          {loading ? "重置中..." : "确认重置密码"}
        </button>

        <button
          type="button"
          onClick={() => router.push("/dashboard/forgot-password")}
          className={styles.cancelButton}
        >
          返回上一步
        </button>
      </form>
    </div>
  );
};

export default VerifyCodePage;